package com.system.common.util;

import cn.hutool.crypto.digest.DigestUtil;

public class PasswordUtil {

    private static final char[] array= {'a', 'b', 'c', 'd', 'e', 'f','0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
    private static final int salt_index=5;
    private static final int count_index=15;
    public static String getEncryption(String password){
        //随机盐值
        int index_salt=(int)(Math.random()* array.length);
        char salt = array[index_salt];
        //随机加密次数
        int index_count=(int)(Math.random()* array.length);
        char count = array[index_count];

        String encryptionPassword = password+salt;
        for (int i = 0; i < count; i++) {
            encryptionPassword=DigestUtil.md5Hex(encryptionPassword);
        }
        System.out.println(encryptionPassword);

        StringBuilder strB = new StringBuilder(encryptionPassword);
        strB.insert(salt_index,salt);
        strB.insert(count_index,count);
        System.out.println(strB);
        return strB.toString();
    }

    public static boolean checkPassword(String password,String encryptionPassword){
        //盐值
        char salt = encryptionPassword.charAt(salt_index);
        //加密次数
        char count = encryptionPassword.charAt(count_index);
        String deCode = password+salt;
        for (int i = 0; i < count; i++) {
            deCode = DigestUtil.md5Hex(deCode);
        }
        StringBuilder strB = new StringBuilder(deCode);
        strB.insert(salt_index,salt);
        strB.insert(count_index,count);
        System.out.println(strB);
        return strB.toString().equals(encryptionPassword);
    }

    public static void main(String[] args) {
        System.out.println(getEncryption("zlich"));
        System.out.println(checkPassword("mumu14","1809329a2eba0a3fb20e870659ded6bc6c"));
    }
}
